/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.love.cloud.auth.config;

import com.love.cloud.auth.provider.*;
import com.love.cloud.auth.service.impl.*;
import com.love.cloud.common.security.handler.FormAuthenticationFailureHandler;
import com.love.cloud.common.security.handler.SsoLogoutSuccessHandler;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;

/**
 * @author lengleng
 * @date 2019/2/1 认证相关配置
 */
@Primary
@Order(90)
@Configuration(proxyBeanMethods = false)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

	@Resource
	private MyPhoneOpenCodeServiceImpl myPhoneOpenCodeService;
	@Resource
	private MyUserDetailsServiceImpl myUserDetailsService;
	@Resource
	private MyQRCodeServiceImpl myQRCodeService;
	@Resource
	private MyDingIdServiceImpl myDingIdService;
	@Resource
	private MyDingFreeLoginServiceImpl myDingFreeLoginService;

	@Override
	@SneakyThrows
	protected void configure(HttpSecurity http) {
		http.formLogin().loginPage("/token/login").loginProcessingUrl("/token/form")
				.failureHandler(authenticationFailureHandler()).and().logout()
				.logoutSuccessHandler(logoutSuccessHandler()).deleteCookies("JSESSIONID").invalidateHttpSession(true)
				.and()
				.authorizeRequests().antMatchers("/token/**", "/actuator/**", "/mobile/**").permitAll()
				.antMatchers("/sosAuth/**").permitAll()
				.anyRequest().authenticated().and().csrf().disable();
	}

	@Override
	public void configure(WebSecurity web) {
		web.ignoring().antMatchers("/css/**");
	}


	/**
	 * 添加权限校验和生成的提供者
	 * @param auth
	 * @throws Exception
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		//手机openCode登陆重写
		auth.authenticationProvider(phoneOpenCodeAuthenticationProvider());
		//添加密码模式
		auth.authenticationProvider(daoAuthenticationProvider());
		//添加钉id模式
		auth.authenticationProvider(dingIdAuthenticationProvider());
		//添加扫码模式
		auth.authenticationProvider(qRCodeAuthenticationProvider());
		//添加浙政钉免登
		auth.authenticationProvider(dingFreeLoginAuthenticationProvider());
	}

	/**
	 * 扫码模式提供者
	 * @return
	 */
	public QRCodeAuthenticationProvider qRCodeAuthenticationProvider(){
		QRCodeAuthenticationProvider provider = new QRCodeAuthenticationProvider();
		// 设置userDetailsService
		provider.setUserDetailsService(myQRCodeService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		return provider;
	}


	/**
	 * 手机openCode模式提供者
	 * @return
	 */
	public PhoneOpenCodeAuthenticationProvider phoneOpenCodeAuthenticationProvider(){
		PhoneOpenCodeAuthenticationProvider provider = new PhoneOpenCodeAuthenticationProvider();
		// 设置userDetailsService
		provider.setUserDetailsService(myPhoneOpenCodeService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		return provider;
	}

	/**
	 * 钉id模式提供者
	 * @return
	 */
	public DingIdAuthenticationProvider dingIdAuthenticationProvider(){
		DingIdAuthenticationProvider provider = new DingIdAuthenticationProvider();
		// 设置userDetailsService
		provider.setUserDetailsService(myDingIdService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		return provider;
	}

	/**
	 * 浙政钉免登提供者
	 * @return
	 */
	public DingFreeLoginAuthenticationProvider dingFreeLoginAuthenticationProvider(){
		DingFreeLoginAuthenticationProvider provider = new DingFreeLoginAuthenticationProvider();
		// 设置userDetailsService
		provider.setUserDetailsService(myDingFreeLoginService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		return provider;
	}

	/**
	 * 密码模式提供者
	 * @return
	 */
	public MyDaoAuthenticationProvider daoAuthenticationProvider(){
//		DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
		MyDaoAuthenticationProvider provider = new MyDaoAuthenticationProvider();
		// 设置userDetailsService
		provider.setUserDetailsService(myUserDetailsService);
		// 禁止隐藏用户未找到异常
		provider.setHideUserNotFoundExceptions(false);
		return provider;
	}



	@Bean
	@Override
	@SneakyThrows
	public AuthenticationManager authenticationManagerBean() {
		return super.authenticationManagerBean();
	}


	public AuthenticationFailureHandler authenticationFailureHandler() {
		return new FormAuthenticationFailureHandler();
	}

	/**
	 * 支持SSO 退出
	 * @return LogoutSuccessHandler
	 */
	public LogoutSuccessHandler logoutSuccessHandler() {
		return new SsoLogoutSuccessHandler();
	}

	/**
	 * https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated
	 * Encoded password does not look like BCrypt
	 * @return PasswordEncoder
	 */
	@Bean
	public PasswordEncoder passwordEncoder() {
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
	}

}
